// pages/photoResult/photoResult.js
import api from "../../config/api";
import { getUserLocation, getUserPermissions, shareOptions } from "../../utils/access";
import request from "../../utils/request";
import { getXsScreen, jump, parse, getStorage, setStorage, removeStorage, paramSplicing, getBarAndTitleHeight, goBack } from "../../utils/utils";
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 加载loading
    loading: false,
    showIndex:0,
    showMid:true,
    showTake:true,
    secHandData:[
      {brandName:'wewew',minPrice:80,maxPrice:190},
      {brandName:'wewew',minPirce:80,maxPrice:190},
      {brandName:'wewew',minPirce:80,maxPrice:190},
    ],
    iconsList:[
      {src:'https://image-classify.daieco.com/kejian-quanzi/VOtC8qVEX33nb0d3fe8ad997399c95762f8884a530bd.png',show:true,select:true},
      {src:'https://image-classify.daieco.com/kejian-quanzi/99ZlqmNV4QsJb31441fcd3e5e2c788024c5673ab347e.png',show:false,select:false},
      {src:'https://image-classify.daieco.com/kejian-space/paRFyczLs8941888fdf274743bb68f52e123db7e69cd.png',show:false,select:false},
      // {src:'https://image-classify.daieco.com/kejian-space/tRqDw4tzu1D7e84987fa395072b24243e774bf18f646.png',select:false},
      // {src:'https://image-classify.daieco.com/kejian-space/dp4DOIkx4kYu7c7bf7f488ae56f6869fb048c156fa2d.png',select:false},
    ],
    btnList:[
      {
        text1:'可回收物',
        text2:'能卖钱、可回收利用',
        type:1,
        select:false,
      },
      {
        text1:'厨余垃圾',
        text2:'易腐烂、易生细菌',
        type:2,
        select:false,
      },
      {
        text1:'不是垃圾',
        text2:'',
        type:3,
        select:false,
      },
      {
        text1:'其他垃圾',
        text2:'难以辨认的废弃垃圾',
        type:4,
        select:false,
      },
      {
        text1:'有害垃圾',
        text2:'容易污染环境',
        select:false,
        type:5,
      },
      {
        text1:'我不会分',
        text2:'',
        select:false,
        type:6,
      },
    ],
    data:{},
    type1list:{
      'KitchenWaste':{
        'title':'桶内厨余垃圾比例超过80%',
        'name':'厨余垃圾桶',
        'url':'https://image-classify.daieco.com/kejian-quanzi/P231Q7LIKl1Xb873598664fe0757d0a487a3b8dd1254.png',
        'text':'主要用于盛放厨余垃圾的垃圾桶。在家中通常可以摆放在厨房中，便于投放。'
      },
      'EmptyWaste':{
        'title':'垃圾桶桶内物品不足5%',
        'name':'空垃圾桶',
        'url':'https://image-classify.daieco.com/kejian-quanzi/Cf79ANFWFalw5b4f65a9f750542ea269476f899f7a9e.png',
        'text':'居家生活离不开。在家中至少要将“厨余垃圾桶”和“其他垃圾桶”分开使用。'
      },
      'MixedWaste':{
        'title':'桶内垃圾混合比例超过20%',
        'name':'混合垃圾桶',
        'url':'https://image-classify.daieco.com/kejian-quanzi/n5cKozUXlAtv266f4a01c22abcaf722e10a33c6ab1cc.png',
        'text':'还在混合投放垃圾？至少要将“厨余垃圾桶”和“其他垃圾桶”分开使用啊。'
      },
      'OtherWaste':{
        'title':'桶内其他垃圾比例超过80%',
        'name':'其他垃圾桶',
        'url':'https://image-classify.daieco.com/kejian-quanzi/bswMOR4R56BHf7ded377c06f8e7d2a6987bea5598fdd.png',
        'text':'主要用于盛放其他垃圾的垃圾桶。家中客厅、卧室、卫生间均可摆放。'
      },
    },
    type2list:[
      {
        name:'',
        title:'其他垃圾',
        url:'https://image-classify.daieco.com/kejian-quanzi/fPUJ3xEvuSIj108f8cbf42d9c31d74cb431e5a8d6b44.png',
        text:'难以辨识类别的生活垃圾，属于其他垃圾，可以投入其他垃圾桶内。'
      },
      {
        name:'',
        title:'可回收物',
        url:'https://image-classify.daieco.com/kejian-quanzi/sVMCw553bppGe1d625f589ca70fe2f7fc75c649a2fe6.png',
        text:'可回收物分类投放时，应尽量保持清洁干燥，避免污染。'
      },
      {
        name:'',
        title:'厨余垃圾',
        url:'https://image-classify.daieco.com/kejian-quanzi/dHPL84mQlAJt9dcef873754a346fce3cb204f8522a86.png',
        text:'厨余垃圾应从产生时就与其他品类垃圾分开，投放前沥干水分。'
      },
      {
        name:'',
        title:'有害垃圾',
        url:'https://image-classify.daieco.com/kejian-quanzi/YwJMA2taB2Lr98c6676cf6e890a878c6e77e24f8f339.png',
        text:'有害垃圾投放时应保证器物完整，避免二次污染。'
      },
      {
        name:'',
        title:'无分类结果',
        url:'https://image-classify.daieco.com/kejian-quanzi/4UcrFJv2z5ryc887854c44d3f6f0163cb65fb77960ad.png',
        text:'很抱歉啊！小K同学还不知道这个属于什么垃圾。'
      },
    ],
    // 空间ID
    spaceId: null,
    // 空间列表
    spaceData: [],
    // 容器ID
    containerId: null,
    // 容器列表
    containerData: [],
    // 容器选中项
    containerIndex: 0,
    inputValue:'',
    params:{
      itemName:'',
      garbageType:0,
      imageUrl:'',
      remark:''
    },
    // 桶内成分分析数据
    ingredientData: {},
    // 是否是小屏幕尺寸
		...getXsScreen(),
    //跳转小程序
    loadMiniProgram:false,
    // 信号栏高度
    ...getBarAndTitleHeight(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.options = options
    const { result, ...ingredientData } = options
    let {type1list,type2list,params,inputValue} = this.data
    if(options.result){
      let result = parse(options.result)
      console.log('result',result);
      params.imageUrl = options.url

      if(result.type == 1){
        params.itemName = type1list[result.name].name
        this.setData({
          data: {
            type: 1,
            ...type1list[result.name]
          },
          ingredientData,
          inputValue:type1list[result.name].name,
          params
        })
      }else{
        let name = result.name.split(',')
        console.log('name',name);
        let data = type2list.find(item=>{
          return item.title == name[1]
        })
        data.name = name[0]
        data.type = 2
        inputValue = name[0]
        params.itemName = name[0]
        console.log('data',data);

        //可回收物才获取二手价格
        if(name[1] == "可回收物"){
          this.getReferencePrice(name[0])
        }
        // 除了厨余垃圾才获取空间列表
        if(name[1] !== '厨余垃圾'){
          // this.getPicList()
        }
        
        const iconIndex = getStorage('iconIndex')
        if (iconIndex) {
          this.clickRightImage({
            currentTarget: {
              dataset: {
                index: +iconIndex
              }
            }
          })
          removeStorage('iconIndex')
        }

        this.setData({
          data,
          params,
          inputValue
        })
      }
    }
  },

  //获取二手参考价格
  getReferencePrice: async function(name){
    let {iconsList} = this.data
    const res = await request.get(api.getReferencePrice, {name});
    console.log('esres',res);

    if(res?.data?.length){
      iconsList[1].show = true
      this.setData({
        secHandData:res.data,
        iconsList
      })
    }
  },

  // 获取空间&容器列表
  async getPicList(params) {
    let { iconsList } = this.data
    let res = null
    if (params?.containerList) {
      res = {
        data: params?.containerList
      }
    } else {
      res = await request.get(
        params ? api.containerList : api.spaceList,
        params ? { storageSpaceId: params.id } : {}
      )
    }
    console.log(params ? '容器' : '空间', res)
    const spaceList = (res?.data?.spaceData || [])
      .filter(item => item.containerNum)

    if(!params) {
      if (spaceList?.length) {
        iconsList[2].show = true
        this.setData({
          spaceData: spaceList.map(item => ({
            ...item,
            name: item.spaceName,
          })
          ),
          iconsList
        })
        this.getPicList(spaceList?.[0])
      }
    } else {
      this.setData({
        containerData: (res?.data || []).map(item => ({
          ...item,
          name: item.containerName,
        })),
        containerIndex: 0,
        spaceId: params.id,
        containerId: res?.data?.[0]?.id
      })
    }
  },

  //显示反馈
  hideMid:function(){
    if (!app.isLogin()) {
      this.toLogin()
      return
    }
    let {showMid} = this.data
    this.setData({
      showMid:!showMid,
      showTake:!showMid,
    })
  },

  //选择反馈选项
  selectTab:function(e){
    let {params} = this.data
    let index = e.currentTarget.dataset.index
    let { btnList } = this.data
    btnList.map((item,i)=>{
      item.select = i==index
    })

    let remark = ''
    let garbageType = 0
    if(index==2){
      remark = '不是垃圾'
    }else if(index==5){
      remark = '我不会分'
    }else if(index<2){
      garbageType = index+1
    }else{
      garbageType = index
    }
    this.setData({
      btnList,
      params:{...params,remark,garbageType}
    })
  },
  //输入框变化
  onInputChange:function(e){
    console.log('e',e);
    let value = e.detail.value
    let {params} = this.data
    params.itemName = value
    this.setData({
      params,
      inputValue:value
    })
  },
  //提交
  subLimit: async function(){
    console.log(111);
    let {params} = this.data
    if(params.itemName==''){
      wx.showToast({
        title: '请输入名称',
        icon:'none'
      })
    }else{
      const res = await request.post(api.userFeedback, params);
      if (res?.httpStatus === 200) {
        wx.showToast({
          title: "提交成功!",
          icon: "success",
          duration: 1500,
        });
        this.setData({
          showMid:true,
          showTake:true
        });
      }
    }
  },
  //关闭反馈面板
  closeMidC:function(){
    let {showMid} = this.data
    this.setData({
      showMid:!showMid,
      showTake:true,
    })
  },
  //点击右侧图标切换
  clickRightImage:function(e){
    let { iconsList } = this.data
    let index = e.currentTarget.dataset.index
    // iconsList[index].select = true
    this.iconIndex = index
    iconsList.map((item,i)=>{
      item.select = i==index
    })
    this.setData({
      iconsList,
      showIndex:index
    })
  },

  // 去登陆
  toLogin() {
    if (this.iconIndex) {
      setStorage('iconIndex', this.iconIndex)
    }
    setStorage('redirectPath', '/pages/photoResult/photoResult')
    setStorage('redirectParams', paramSplicing('', this.options))
    app.login()
  },

  //返回
  navigationBack:()=>{
    goBack()
  },

  //去拍照
  takePhoto() {
    this.modal.hide()
    wx.navigateBack({
      delta: 2,
    })
  },
  // 跳转桶内成分分析页面
  jumpAnalyze() {
    const { ingredientData } = this.data
    jump('bucketAnalyse', ingredientData)
  },
  // 跳转预约回收页面
  jumpRecycle() {
    if (!app.isLogin()) {
      this.toLogin()
      return
    }
    jump('recycleFurniture')
  },
  // 获取用户信息
  async getInfo() {
    if (!app.isLogin()) return
		const userId = getStorage("userId");
		if (userId) {
			const res = await request.get(
				api.homeDetail,
				{ userId },
				{ loading: false }
			);
			//重新赋值 缓存信息
			setStorage("communityBind", res?.data.communityBind || false);
			setStorage("communityName", res?.data.communityName || " ");
			setStorage("communityId", res?.data.communityId || " ");
			this.setData({
				communityBind: res?.data.communityBind,
			});
		}
	},
  // 跳转二手置换
  jumpApplets() {
    if (!app.isLogin()) {
      this.toLogin()
      return
    }
    const { params, communityBind } = this.data
    if (getUserLocation()) {
      if (!communityBind) {
        wx.showModal({
          content: "请先绑定小区!",
          confirmText: "去绑定",
          success: function (res) {
            if (res.confirm) {
              jump('idleCommunityList')
            }
          },
        });
      } else {
        jump('idleRelease', {
          url: params.imageUrl,
          isTakePhotos: 1
        })
      }
    } else {
      getUserPermissions('userLocation', (res) => {
        if (res) {
          this.jumpApplets()
        }
      })
    }
  },
  // 展示草稿保存提示
 async showDraftModal(params){
  wx.showModal({
    title: '提示',
    content: '是否保存草稿？',
    confirmText: '保存',
    cancelText: '不保存',
   async success(res) {
       if (res.confirm) { //保存草稿
       let res= await request.post(api.addTempGoods, params,{loading: true})
       if(res.httpStatus=== 200){
        wx.showToast({
          title: '保存成功',
          icon: 'none'
        })
       }
      } else if (res.cancel) {//删除草稿
        if(!params.id) return //没有草稿
        let res= await request.post(api.deleteTempGoods, {id: params.id},{loading: true})
         if(res.httpStatus=== 200){
          wx.showToast({
            title: '删除成功',
            icon: 'none'
          })
        }
      }
    }
  })
},
  // 图片推荐变化
  async picChange(e) {
    const picType = e?.target.dataset.type
    const { type, data } = e?.detail || {}
    // 标题切换
    if (type === 'title') {
      // 空间
      if (picType === 'space') {
        this.getPicList(data)
      } else {
        // 容器
        this.setData({
          containerId: data.id
        })
      }
    } else {
      // 图片切换
    }
  },
  // 收纳
  async storage() {
    if (!app.isLogin()) {
      this.toLogin()
      return
    }
    const { loading, containerId, spaceId, params, data } = this.data
    if (loading) return
    this.setData({
      loading: true
    })
    const parameter = {
      spaceId,
      containerId,
      aiResult: data.name,
      itemImgUrl: params?.imageUrl
    }
    const res = await request.post(
      api.goodsAdd,
      parameter
    )
    console.log('收纳参数', parameter)
    console.log('收纳', res)
    if (res?.httpStatus === 200) {
      this.modal.show()
    }
    
    this.setData({
      loading: false
    })
  },
  // 跳转容器详情
  jumpContainer() {
    this.modal.hide()
    wx.navigateTo({
      url: `/pages/acceptIndex/acceptIndex?id=${this.data.containerId}`,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.modal = this.selectComponent('#modal')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  // 用户点击右上角分享
	onShareAppMessage(e) {
		return shareOptions('default', e)
	},
})